package org.barman.servlet;

import java.io.IOException;
import java.sql.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.barman.dao.UserDAO;
import org.barman.exception.CustomMessageException;
import org.barman.pojo.User;
import org.barman.pojo.UserRole;

@WebServlet("/ManageUserServlet")
public class ManageUserServlet extends ExceptionHandlingHttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doExceptionHandledPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, CustomMessageException {

		String action = request.getParameter("action");

		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String verifyPassword = request.getParameter("verifyPassword");
		String email = request.getParameter("email");
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		String role = request.getParameter("role");

		if (username == null || "".equals(username)) {
			throw new CustomMessageException("invalid username");
		}

		if (password == null || "".equals(password)) {
			throw new CustomMessageException("invalid password");
		}

		if (verifyPassword == null || "".equals(verifyPassword) || !password.equals(verifyPassword)) {
			throw new CustomMessageException("invalid verify password");
		}

		if (email == null || "".equals(email)) {
			throw new CustomMessageException("invalid email");
		}

		if (role == null || "".equals(role) || UserRole.getRole(role) == null) {
			throw new CustomMessageException("invalid role");
		}

		UserDAO userDAO = new UserDAO();
		User user = new User();
		
		if ("add".equals(action)) {

			user.setUsername(username);
			user.setPassword(password);
			user.setEmail(email);
			user.setFirstName(firstName);
			user.setLastName(lastName);
			user.setRole(UserRole.getRole(role));
			user.setCreated(new Date(System.currentTimeMillis()));

			userDAO.insert(user);
		} else if ("edit".equals(action)) {
			
			int userId = Integer.parseInt(request.getParameter("id"));
			
			user = userDAO.get(userId);
			user.setUsername(username);
			user.setPassword(password);
			user.setEmail(email);
			user.setFirstName(firstName);
			user.setLastName(lastName);
			user.setRole(UserRole.getRole(role));;
			user.setModified(new Date(System.currentTimeMillis()));

			userDAO.update(user);
			request.setAttribute("flash.message", "item updated successfully");
		}

		
		request.setAttribute("flash.message", "user added successfully");

		response.sendRedirect("admin/main.jsp");
	}
}
